package com.google.code.avajhelpdesk;

import java.util.Set;

import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.google.code.avajhelpdesk.entities.User;
import com.google.code.avajhelpdesk.exceptions.auth.AuthenticationException;
import com.google.code.avajhelpdesk.model.GenericLoadableDetachableModel;
import com.google.code.avajhelpdesk.persistence.IGenericDAO;
import com.google.code.avajhelpdesk.services.UserService;

public class MyWebSession extends AuthenticatedWebSession {

	/**
	 * Generated id
	 */
	private static final long serialVersionUID = -7519917230823832449L;

	@SpringBean
	private UserService userService;

	private GenericLoadableDetachableModel<User> detachedUser;
	
	public MyWebSession(Request request) {
		super(request);
		InjectorHolder.getInjector().inject(this);
	}

	@Override
	public boolean authenticate(String login, String password) {
		try {
			detachedUser = new GenericLoadableDetachableModel<User>(
					userService.authenticateUser(login, password));
			return true;
		} catch (AuthenticationException e) {
			return false;
		}
	}

	@Override
	public Roles getRoles() {
		if (isSignedIn()) {
			Set<String> roles = getUser().getRoles();
			String[] rolesArray = new String[roles.size()];
			roles.toArray(rolesArray);
			return new Roles(rolesArray);
		} else {
			return new Roles();
		}
	}
	
	public User getUser() {
		detachedUser.detach();
		return detachedUser.getObject();
	}

}
